﻿/// <reference path="../../../Proggy/Scripts/jquery-1.7.2-vsdoc.js" />
/// <reference path="../../../Proggy/Content/ThirdParty/jquery-ui-1.8.21.custom/js/jquery-ui-1.8.21.custom.min.js" />
/// <reference path="../../../Proggy/Content/Scripts/ProggyCore.js" />
/// <reference path="Proggy.CorePropertyTypes.js" />


// static
Proggy.CorePropertyTypes.Static.DragAndDrop = {

    BeforeUpdateMethods: [],

    AddToBeforeUpdateMethods: function (method) {
        this.BeforeUpdateMethods.push(method);
    }

};

//
Proggy.CorePropertyTypes.DragAndDrop = function () {

    /**** vars *****/
    var _areaId, _saveDataId, _saveDataDiv, _iframeId, _htmlDivId, _iframe, _iframeInner, _htmlDiv, _propNameStart;
    var _dandLinks, _sortable, _contents, _contentsBody, _dandItems, _addNew;
    var _currentlyEditing;



    /***** functions *****/

    // remove from cache
    var removePartFromCache = function (url, tempId, callback) {

        //
        jQuery.ajax(url, {

            type: "POST",
            async: false,
            data: {
                tempId: tempId
            },
            success: function (r, s, x) {
                console.log(r);
                callback(r, s, x);
            }

        });

    }

    // sets _dandItems
    var setDandItems = function () {
        _dandItems = _sortable.find(".dand-item");
    };

    // takes input els from iframe and puts in parents
    var addInputElsToParent = function () {

        // clear
        _saveDataDiv.html("");

        // get inputs
        var inputs = [];

        // set dand items
        setDandItems();

        // iterate dands
        jQuery.each(_dandItems, function (i, item) {

            // create first part
            var firstPart = "<input type=\"hidden\" name=\"" + _propNameStart + ".AddedDragAndDropItems[" + i + "].";

            // get config data
            var configDataString = jQuery(item).data("configdata").toString().substring("__CONFIGDATA".length);
            //console.log(configDataString);

            // create html
            inputs.push(firstPart + "Float\" value=\"" + jQuery(item).data("float") + "\" />");
            inputs.push(firstPart + "Clear\" value=\"" + jQuery(item).data("clear") + "\" />");
            inputs.push(firstPart + "Margin\" value=\"" + jQuery(item).data("margin") + "\" />");
            inputs.push(firstPart + "Width\" value=\"" + jQuery(item).data("width") + "\" />");
            inputs.push(firstPart + "ConfigData\" value='" + configDataString + "' />");
            inputs.push(firstPart + "PartName\" value=\"" + jQuery(item).data("partname") + "\" />");
            inputs.push(firstPart + "Float\" value=\"" + jQuery(item).data("float") + "\" />");
            inputs.push(firstPart + "UniqueId\" value=\"" + jQuery(item).attr("id") + "\" />");
            inputs.push(firstPart + "NodeId\" value=\"" + jQuery(item).data("nodeid") + "\" />");

        });

        // move
        jQuery.each(inputs, function (i, input) {
            _saveDataDiv.append(input);
        });

        // check
        //console.log(_saveDataDiv);
        //console.log(inputs);
    };

    // kills links and forms in iframe
    var killLinksAndForms = function () {

        // kill links
        jQuery(_iframeInner).find("div.dand-item-part").find("a").click(function (e) {
            e.preventDefault();
            return false;
        });

        // kill forms
        jQuery(_iframeInner).find("div.dand-item-part").find("form").submit(function (e) {
            e.preventDefault();
            return false;
        });

    };

    // binds links for each added part
    var bindDandLinks = function () {

        // private
        function bindDelete() {

            // get link
            var links = jQuery(_sortable).find("a.dand-delete-link");

            // iterate
            links.each(function () {

                // get link
                var link = jQuery(this);

                // unbind
                link.unbind();

                // bind
                link.click(function (e) {

                    // 
                    e.preventDefault();

                    // confirm
                    if (confirm("Are you sure you want to delete this part?\n\n(Note: You will still need to click \"Save\" above after clicking \"OK\" here).")) {

                        // get data
                        var url = link.attr("href");
                        var tempId = link.data("tempid");

                        // remove
                        removePartFromCache(url, tempId, function (r, s, x) {

                            // find parent
                            var theParent = link.parent().parent().parent();

                            // remove
                            theParent.remove();

                            // reset
                            addInputElsToParent();

                        });

                    };

                });

            });
        };

        // private
        function bindMoveLeft() {

            // find links
            var links = jQuery(_sortable).find("a.dand-back-link");

            // unbind
            links.unbind("click");

            // iterate
            links.each(function () {

                // find link
                var link = jQuery(this);

                // bind
                link.click(function (e) {

                    //
                    e.preventDefault();

                    // find item
                    var theItem = link.parent().parent().parent("div.dand-item:first");

                    // get index
                    var index = theItem.index();

                    // get numbers
                    var oldNumber = index + 1;
                    var newNumber = index;

                    // find prev
                    var thePrevious = theItem.prev(".dand-item:first");

                    // check
                    if (thePrevious.size() == 1) {

                        // move
                        thePrevious.before(theItem);
                        thePrevious.find("div.dand-item-header-links:first > span:first").text("Item " + oldNumber + ": ");
                        theItem.find("div.dand-item-header-links:first > span:first").text("Item " + newNumber + ": ");

                        // rebind
                        addClear();
                        addInputElsToParent();
                        bindDandLinks();

                    };
                });
            });
        };

        // private
        function bindMoveRight() {

            // find links
            var links = jQuery(_sortable).find("a.dand-forward-link");

            // unbind
            links.unbind("click");

            // iterate
            links.each(function () {

                // find link
                var link = jQuery(this);

                // bind
                link.click(function (e) {

                    //
                    e.preventDefault();

                    // find item
                    var theItem = link.parent().parent().parent("div.dand-item:first");

                    // get index
                    var index = theItem.index();

                    // get numbers
                    var oldNumber = index + 1;
                    var newNumber = index + 2;

                    // find prev
                    var theNext = theItem.next(".dand-item:first");

                    // check
                    if (theNext.size() == 1) {

                        // move
                        theNext.after(theItem);
                        theNext.find("div.dand-item-header-links:first > span:first").text("Item " + oldNumber + ": ");
                        theItem.find("div.dand-item-header-links:first > span:first").text("Item " + newNumber + ": ");

                        // rebind
                        addClear();
                        addInputElsToParent();
                        bindDandLinks();

                    };
                });
            });
        };

        // private
        function bindEdit() {

            // get links
            var links = jQuery(_sortable).find("a.dand-edit-link");

            // unbind
            links.unbind("click");

            // iterate
            links.each(function () {

                // get link
                var link = jQuery(this);

                // set status
                window.DAND_CONFIGURE_STATUS = "edit";

                // bind
                link.click(function (e) {

                    // set editing
                    _currentlyEditing = link.parent().parent().parent();

                    // load
                    Proggy.Static.InitialLoadIntoLightbox(link, e);
                });

            });

        };

        // bind
        bindEdit();
        bindDelete();
        bindMoveLeft();
        bindMoveRight();
    };

    // bind on load new part
    var bindOnSelectNewPart = function () {

        // add to static methods
        Proggy.Static.AddToBeforeLightboxContentShowMethods(function () {

            // get dialog
            var dialog = jQuery(".ui-dialog");

            // check
            if (dialog.size() > 0) {

                // get els
                var lb = dialog.children(".proggy-lb:eq(0)");
                //console.log(lb);
                var lbInner = lb.children(".proggy-lb-inner:eq(0)");
                //console.log(lbInner);
                var dand = lbInner.children(".dand-item:eq(0)");
                //console.log(dand);

                // 
                if (dand.size() > 0) {

                    // show load
                    Proggy.Static.ShowTempLoader(lb, lbInner, function () {

                        //console.log(window.DAND_CONFIGURE_STATUS);
                        //console.log(_currentlyEditing);


                        // check status
                        if (window.DAND_CONFIGURE_STATUS == "add") {

                            // get item no
                            var itemNo = _sortable.find("div.dand-item").size() + 1;

                            // add item no
                            dand.find("div.dand-item-header-links:first > span:first").text("Item " + itemNo + ": ");

                            // move dand
                            _sortable.append(dand);
                        };

                        // check status
                        if (window.DAND_CONFIGURE_STATUS == "edit") {

                            // get text
                            var theText = _currentlyEditing.find("div.dand-item-header-links:first > span:first").text();

                            // add item no
                            dand.find("div.dand-item-header-links:first > span:first").text(theText);

                            // replace
                            _currentlyEditing.replaceWith(dand);
                        };

                        // set
                        //setDandItems();

                        // re-register inputs
                        addInputElsToParent();

                        // kill forms again
                        killLinksAndForms();

                        // rebind
                        bindDandLinks();

                        //add clear
                        addClear();

                        // hide loader
                        Proggy.Static.HideLoader(true, lb, lbInner);

                    });

                };


            };

        });
    };

    // add "clear" area to content
    var addClear = function () {
        jQuery(_sortable).find("span.dand-clear").remove();
        jQuery(_sortable).append("<span class=\"dand-clear\">&nbsp;</span>");
    };

    // bind to before unload global function
    var bindToBeforeUnload = function () {

        // start counter
        var counter = 0;

        // inner function
        var innerFunc = function (deletes_, callback) {

            // get link
            var theLink = jQuery(deletes_[counter]);

            // check
            if (theLink.size() == 1) {

                // ok so remove
                // get data
                var url = theLink.attr("href");
                var tempId = theLink.data("tempid");

                // remove
                removePartFromCache(url, tempId, function (r, s, x) {

                    // incr
                    counter++;

                    // run again
                    innerFunc(deletes_, callback);
                });

            }
            else {
                callback();
            }
        };

        // create function
        var theFunc = function (callback) {

            // find links
            var deletes = jQuery(_sortable).find("a.dand-delete-link");

            // run
            innerFunc(deletes, callback);

        };

        // bind
        Proggy.Static.AddToBeforeUnloadMethods(theFunc);
    };

    // bind hovers
    var bindHovers = function () {

        // mouse enter
        jQuery(_contentsBody).on("mouseenter", "div.dand-item", function (e) {

            // get this
            var ts = jQuery(this);

            // add class
            ts.addClass("dand-item-hover");

            // get header
            var header = ts.find("div.dand-item-header:first");

            // get pos
            var headerPos = header.position();

            // set css
            header.css({
                position: "absolute",
                left: headerPos.left,
                top: headerPos.top
            });            

            //alert("TODO: make sure header is visible at all times by checking hover / header position and container size / float etc etc");

        });


        // mouse leave
        jQuery(_contentsBody).on("mouseleave", "div.dand-item", function () {
        
            // get this
            var ts = jQuery(this);
            
            // reposition
            ts.removeClass("dand-item-hover")
            
            // reposition header
            ts.find("div.dand-item-header:first").removeAttr("style");
        });

    };

    // set iframe with initial content
    var setIFrameAndInit = function () {

        // get content
        _htmlDiv = jQuery("#" + _htmlDivId);

        // get html
        var initHtml = _htmlDiv.html();

        // remove html div
        _htmlDiv.remove();

        // set save div
        _saveDataDiv = jQuery("#" + _saveDataId);

        // get iframe
        _iframe = document.getElementById(_iframeId);

        // get iframe inner
        _iframeInner = _iframe.contentDocument || _iframe.contentWindow.document;

        // set
        _iframeInner.write(initHtml);
        _iframeInner.close();

        // set inner
        _contents = jQuery(_iframeInner);
        _contentsBody = _contents.find("body:eq(0)");

        //
        bindHovers();

        // set sortable
        _sortable = _contentsBody.find("#" + _areaId);

        // bind
        //bindToBeforeUnload();

        // add input els
        addInputElsToParent();

        // kill links and forms
        killLinksAndForms();

        // bind on select
        bindOnSelectNewPart();

        // bind dand links
        bindDandLinks();

        // add clear
        addClear();

    };

    //
    var beforeSave = function () {
        // get form
        var form = jQuery("form#dand_configure");

        // check
        if (form.size() == 1) {

            var theFunc = function () {
                jQuery.each(Proggy.CorePropertyTypes.Static.DragAndDrop.BeforeUpdateMethods, function (i, method) {
                    method();
                });
            };

            // bind
            form.submit(function () {

                //
                Proggy.Static.ShowLoader(function (lb, lbInner) {

                    // marker
                    saving = true;

                    //
                    if (true) {

                        // unbind submit
                        form.unbind("submit");

                        // iterate methods
                        theFunc();

                        //
                        window.setTimeout(function () {

                            // hide loader
                            Proggy.Static.HideLoader(true, lb, lbInner, function () {
                                //
                                form.trigger("submit");

                            });


                        }, 1000);
                    };
                });

                return false;

            });
        }
    };

    // init
    this.Init = function (propNameStart, areaId, iframeId, htmlDivId, saveDataId) {

        // set variables
        _propNameStart = propNameStart;
        _areaId = areaId;
        _saveDataId = saveDataId;
        _iframeId = iframeId;
        _htmlDivId = htmlDivId;

        // bind save button methods
        Proggy.Static.AddToBeforeLightboxContentShowMethods(beforeSave);

        // kicks off everything
        setIFrameAndInit();
    };

};

